package cn.iocoder.yudao.module.erp.framework.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;

@Component
public class SpringHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName) {
        return (T) getContext().getBean(beanName);
    }

    public static <T> T getBean(Class<T> classType) {
        return getContext().getBean(classType);
    }

    public static <T> T getBean(Class<T> classType, Predicate<T> filter) {
        return getBeans(classType).stream().filter(filter).findFirst()
                .orElseThrow(() -> new NoSuchBeanDefinitionException(classType));
    }

    public static <T> List<T> getBeans(Class<T> classType) {
        Map<String, T> beansOfType = getContext().getBeansOfType(classType);
        return new ArrayList<>(beansOfType.values());
    }

    public static ApplicationContext getContext() {
        return Optional.ofNullable(applicationContext).orElseThrow(() -> new ApplicationContextException("applicationContext cannot be null"));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringHolder.applicationContext = applicationContext;
    }
}
